﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using SimpleTCP;


namespace VSWClient.Tcp
{
    public class TcpClient
    {
        #region private property
        private SimpleTcpClient client;

        #endregion

        #region public property

        public bool Connected { get; set; } = false;

        public string IP { get; set; }

        public int Port { get; set; }

        public Encoding Encoding { get; set; } = Encoding.UTF8;
        #endregion

        #region construct
        public TcpClient()
        {
            client = new SimpleTcpClient();
        }

        public TcpClient(string ip,int port)
        {
            client = new SimpleTcpClient();
            IP = ip;
            Port = port;			
        }

        #endregion

        #region recieve event

        public event EventHandler<DealMessageHandlerArgs> DealMessageHandler;

        #endregion

        #region connect/disconnect

        public bool Connect()
        {
            try
            {
				client.StringEncoder =Encoding;								
				client.Connect(IP, Port);
                client.DataReceived += Client_DataReceived;		
				Connected = true;
                return Connected;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        private void Client_DataReceived(object sender, Message e)
        {
            string[] message = GetMessages(e.MessageString);
            if(message!=null)
            {
                DealMessageHandler?.Invoke(this, new DealMessageHandlerArgs(message));
            }
        }

        private string lastMessage = string.Empty;
        string[] GetMessages(string message)
        {
			//如果是一整条指令
			if (message.EndsWith("##"))
			{
				if (lastMessage == string.Empty)
					return Regex.Split(message, "##");
				else
				{
					string str = string.Format("{0}{1}", lastMessage, message);
					lastMessage = string.Empty;
					return Regex.Split(message, "##");
				}
			}
			//如果不是一整条指令
			else
			{
				string[] str = Regex.Split(message, "##");
				//不完整指令内不包含一条完整指令
				if (str.Length == 1)
				{
					if (lastMessage == string.Empty)
						lastMessage = message;
					else
						lastMessage = string.Format("{0}{1}", lastMessage, message);
					return null;
				}
				//不完整指令内包含几条完整指令
				else
				{
					if (lastMessage == string.Empty)
					{
						lastMessage = str.Last();
						string[] msg = new string[str.Length - 1];
						Array.Copy(str, msg, str.Length - 1);
						return msg;
					}
					else
					{
						lastMessage = string.Format("{0}{1}", lastMessage, str.Last());
						string[] msg = new string[str.Length - 1];
						Array.Copy(str, msg, str.Length - 1);
						return msg;
					}
				}

			}
		}


        public void Disconnect()
        {
            //未与服务器连接前client为null
            if (client != null)
            {
                client.Disconnect();
                client.Dispose();
                Connected = false;
            }
        }

        #endregion

        #region send recieve
        public void SendMessage(string commandType, string identity, string para)
        {
            try
            {
                string message = string.Format("{0};{1};{2};{3}##", commandType, identity, 
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), para);
                client.Write(message);
            }
            catch(Exception ex)
            {
				System.Windows.Forms.MessageBox.Show(ex.Message);
				throw ex;
            }
        }

        #endregion
    }

    public class DealMessageHandlerArgs:EventArgs
    {
        public string[] Message { get; set; }

        public DealMessageHandlerArgs(string[] message)
        {
            Message = message;
        }
    }

}
